package example.controller;

import example.dao.UserDao;
import example.model.User;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/userList")
public class UserListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final int PAGE_SIZE = 3; // 每页显示的记录数

    UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int currentPage = 1; // 当前页码，默认第一页
        String pageParam = request.getParameter("page");
        if (pageParam != null && !pageParam.isEmpty()) {
            currentPage = Integer.parseInt(pageParam);
        }

        String queryParam = request.getParameter("query"); // 获取查询条件参数
        if (queryParam == null) {
            queryParam = ""; // 设置默认值为空字符串
        }

        String sql = getSqlWithQuery(queryParam); // 根据查询条件获取对应的SQL语句
        int offset = (currentPage - 1) * PAGE_SIZE;
        List<User> userList = userDao.getUserList(sql, offset, PAGE_SIZE);

        int totalCount = getTotalCount(queryParam); // 根据查询条件获取总记录数
        int totalPages = (totalCount + PAGE_SIZE - 1) / PAGE_SIZE; // 计算总页数

        request.setAttribute("userList", userList);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("query", queryParam); // 将查询条件也设置为属性传递给JSP页面
        request.getRequestDispatcher("/userList.jsp").forward(request, response);
    }

    private String getSqlWithQuery(String queryParam) {
        StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM user");
        if (queryParam != null && !queryParam.isEmpty()) {
            sqlBuilder.append(" WHERE username LIKE '%").append(queryParam).append("%'"); // 按用户名模糊查询
        }
        sqlBuilder.append(" LIMIT ?, ?");
        return sqlBuilder.toString();
    }

    private int getTotalCount(String queryParam) {
        StringBuilder sqlBuilder = new StringBuilder("SELECT COUNT(*) FROM user");
        if (queryParam != null && !queryParam.isEmpty()) {
            sqlBuilder.append(" WHERE username LIKE '%").append(queryParam).append("%'"); // 按用户名模糊查询统计数量
        }
        return userDao.getTotalCount(sqlBuilder.toString());
    }
}